// pages/bandDetails/bandDetails.js
const App = getApp()
var util = require('../../utils/util');

var QQMapWX = require('./qqmap/qqmap-wx-jssdk.js');

const teacherReduceTypeList = {
  1: '迟到',
  2: '步骤未完成',
  3: '位置异常',
  4: 'vip签到异常',
}

var locationRetry = 0

var intervalId = null

var tabs = [{
    name: '签到',
    value: 1
  },
  {
    name: '点名',
    value: 2
  },
  {
    name: '布置作业',
    value: 3
  },
  {
    name: '课堂反馈',
    value: 4
  },
  {
    name: '作业点评',
    value: 5
  },
]
Page({
  /**
   * 页面的初始数据
   */
  data: {
    teacherReduceTypeList: teacherReduceTypeList,
    tabList: [],
    currentItem: 1,
    Time: '时间获取中...',
    cid: '',
    courseDetail: {}, //课程详情
    callCurrentType: 0,
    callInfoList: [], //学生点名列表
    homeWorkDetail: {
      homeWorkContent: '', //作业内容
    }, //作业详情
    courseFeedback: {
      // feedbackPictureUrl: "", //反馈图片地址
      feedbackVideoUrl: "", //反馈视频地址
      // classSummary: "", //课堂总结
      // courseContent: "", //课堂教学内容
    }, //课程反馈
    professionalScore: {
      name: '专业',
      value: 0,
      type: 'professionalScore'
    }, //专业
    attitudeScore: {
      name: '态度',
      value: 0,
      type: 'attitudeScore'
    }, //态度
    reviewList: [], //作业列表
    qqmapsdk: null, //腾讯地图sdk
    singStatus: null, //打卡状态
    singTimeStatus: false,
    local: null, // 定位位置信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    let qqmapsdk = new QQMapWX({
      key: 'AYHBZ-4426T-5LWXA-LDVQL-L77NJ-DMBNM'
      // 腾讯地图sdk
    });
    if (options && options.id) {
      let tabList = tabs
      if (options.type == 1) {
        console.log(tabList)
        tabList = tabList.slice(0, 1)
      }
      this.setData({
        cid: options.id,
        courseType: options.type,
        tabList: tabList,
        qqmapsdk: qqmapsdk
      })
      this.getDetail(options.id, options.type)
    }
    intervalId = setInterval(function () {
      let canSignTime = new Date(`${that.data.courseDetail.yearMonthDay} ${that.data.courseDetail.startTime}`)
      // let canSignTime = new Date(`2024-02-20 22:16:20`) //测试用
      that.setData({
        Time: util.currentTime(),
        singTimeStatus: ((canSignTime.getTime() - new Date().getTime()) <= 3600000)
      });
    }, 1000);
  },
  onUnload() {
    // 生命周期函数--监听页面卸载
    clearInterval(intervalId)
  },
  getDetail: async function (id, type) {
    // 获取课程详情-包含vip签到详情
    let data = await App.$axios.request({
      url: `/teacher/curriculum/timetableDetaildInfo`,
      method: 'GET',
      loading: true,
      data: {
        timeTableDetailId: id,
        curriculumType: type
      }
    })
    if (data) {
      this.setData({
        courseDetail: data
      })
    }
    if (type == 1) {
      let sign = await this.getVipSignInfo(id)
      this.setData({
        ...this.data.courseDetail,
        ...sign
      })
    }
    if (type == 2) {
      await this.getBandSign(id)
      this.setData({
        currentItem: this.data.courseDetail.curriculumStup < 6 ? this.data.courseDetail.curriculumStup : 5,
        tabList: tabs.slice(0, this.data.courseDetail.curriculumStup)
      })
    }
    // if (this.data.courseDetail.curriculumStup == 6) return
    this.getTabData(this.data.currentItem)
    if (this.data.courseDetail.curriculumStup > 3) return
    this.getLocationStraight()
  },

  async getBandSign(id) {
    // 获取团课签到信息
    let data = await App.$axios.request({
      url: `/teacher/big/signInfo/${id}`,
      method: 'GET',
      loading: true,
    })
    if (data) {
      this.setData({
        courseDetail: {
          ...this.data.courseDetail,
          ...data
        }
      })
    }
    if (this.data.courseDetail.curriculumStup > 1) {
      let sign = await this.getBigSignInfo(id)
      this.setData({
        ...this.data.courseDetail,
        ...sign
      })
    }
  },

  async getBigSignInfo(id) {
    // 获取团课签到信息
    let data = await App.$axios.request({
      url: `/teacher/big/signInfo/${id}`,
      method: 'GET',
      loading: true,
    })
    return data
  },

  async getVipSignInfo(id) {
    // 获取vip课签到信息
    let data = await App.$axios.request({
      url: `/teacher/vip/signInfo/${id}`,
      method: 'GET',
      loading: true,
    })
    return data
  },

  async getLocationStraight(e) {
    // 获取位置距离信息
    if (e) {
      locationRetry = 0
    }
    let that = this
    let signLocation = this.data.courseDetail.location
    // let signLocation = '30.2084,120.21201' //测试用
    console.log(signLocation)
    if (!signLocation) {
      setTimeout(() => {
        that.getLocationStraight()
      }, 2000);
      return
    }
    this.data.qqmapsdk.calculateDistance({
      // from: e.detail.value.start || '', //若起点有数据则采用起点坐标，若为空默认当前地址
      to: signLocation, //终点坐标
      mode: 'straight', // ‘driving’（驾车）、‘walking’（步行） 默认：'walking’ ‘straight’（直线）
      success: (res) => {
        locationRetry = 0
        if (res && res.result.elements[0]) {
          let local = res.result.elements[0]
          let dis = local.distance < 1000
          that.setData({
            singStatus: dis,
            local: local
          })
        }
        setTimeout(() => {
          that.getLocationStraight()
        }, 15000);
      },
      fail: (e) => {
        console.log(e)
        if (locationRetry >= 3) {
          wx.showToast({
            title: '获取位置失败，请重试或联系管理员',
            icon: "none",
            duration: 2500
          })
          return
        }
        locationRetry = locationRetry + 1
        setTimeout(() => {
          that.getLocationStraight()
        }, 15000);
      },
    })
  },

  getLocation: async function (e) {
    // 获取定位
    let that = this
    if (this.data.singStatus == null) {
      wx.showToast({
        title: '未获取到打卡信息，请尝试重新进入或刷新',
        icon: "none",
        duration: 2500
      })
      return
    }
    try {
      // 获取定位
      let local = this.data.local.from
      this.data.qqmapsdk.reverseGeocoder({
        location: `${local.lat},${local.lng}`,
        success: function (res) {
          //成功后的回调
          // res.result.formatted_addresses.recommend 位置名称
          // res.result.address_reference.landmark_l2.location 位置信息
          let singLocation = res.result.address_reference.landmark_l2.location
          console.log(singLocation.lng, singLocation.lat, res.result.formatted_addresses.recommend)
          that.postSignLocation(singLocation.lng, singLocation.lat, res.result.formatted_addresses.recommend)
        },
        fail: (e) => {
          console.log(e)
          wx.showToast({
            title: '定位失败，请重试',
            icon: 'none',
            duration: 3000
          })
        }
      })
    } catch (error) {
      console.log(error)
      if (error.errMsg && error.errMsg.indexOf('fail auth deny')) {
        wx.showToast({
          title: '无权限,请进入小程序右上角设置手动开启定位',
          icon: 'none',
          duration: 4000
        })
      }
    }
  },

  async postSignLocation(longitude, latitude, recommend) {
    // 上传定位地址
    let courseType = this.data.courseType
    if (courseType == 1) {
      // vip课程需要上传图片
      // let files = await wx.chooseMedia({
      //   count: 1,
      //   mediaType: ['image'],
      //   sourceType: ['camera'],
      //   camera: 'back',
      // })
      try {
        let files = await wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['camera']
        })
        let file = files.tempFilePaths[0]
        let suffix = file.substring(file.indexOf('.'), file.length)
        // 上传的图片没有后缀，手动添加上后缀
        let url = await App.$axios.request({
          url: `/file/upload`,
          method: 'FILE',
          loading: true,
          filePath: file,
          name: 'file', // 文件字段名，默认为file
          formData: {
            name: `feedbackFile${suffix}`
          }
        })
        let signdata = await App.$axios.request({
          // vip课签到接口
          url: "/teacher/vip/sign",
          method: 'PUT',
          loading: true,
          data: {
            timetableDetailedId: this.data.cid,
            signLocation: `${longitude},${latitude}`,
            signUrl: url,
            signLocationName: recommend,
            signCheck: this.data.singStatus
          }
        })
        if (signdata && signdata.teacherReduceType) {
          // 签到错误提示
          wx.showToast({
            title: `${teacherReduceTypeList[signdata.teacherReduceType]}`,
            icon: 'none',
            duration: 2000
          })
        }
        this.getDetail(this.data.cid, this.data.courseType)
      } catch (error) {
        console.log(error)
      }
    } else {
      // 团课签到（不需要拍照）
      let signdata = await App.$axios.request({
        // 团课签到接口
        url: "/teacher/big/sign",
        method: 'PUT',
        loading: true,
        data: {
          timetableDetailedId: this.data.cid,
          signLocation: `${longitude},${latitude}`,
          signLocationName: recommend,
          signCheck: this.data.singStatus
        }
      })
      if (signdata && signdata.teacherReduceType) {
        // 签到错误提示
        wx.showToast({
          title: `${teacherReduceTypeList[signdata.teacherReduceType]}`,
          icon: 'none',
          duration: 2000
        })
      } else if (signdata && signdata.signLocation) {
        this.getDetail(this.data.cid, this.data.courseType)
      }
    }
  },

  getTime: function (e) {
    // 获取时间
    var that = this;
    var currentTime = util.formatTime(new Date());
  },

  changeTab: function (item) {
    // 切换tab
    let iteminfo = item.currentTarget.dataset.iteminfo
    this.setData({
      currentItem: iteminfo.value
    })
    this.getTabData(iteminfo.value)
  },
  getTabData: async function (index) {
    // 切换调用请求
    switch (index) {
      case 1:

        break;
      case 2:
        this.getCallRollInfo()
        break;
      case 3:
        this.getHomeWork()
        break;
      case 4:
        this.getFeedbackinfo()
        break;
      case 5:
        this.getReviewList()
        break;
      default:
        break;
    }
  },
  async getCallRollInfo() {
    // 获取点名详情列表
    let data = await App.$axios.request({
      url: `/teacher/big/callRollInfo/${this.data.cid}`,
      method: 'GET',
      loading: true,
    })
    console.log(data)
    if (data.curriculumBigTeacherCallRollMap && data.curriculumBigTeacherCallRollMap.length) {
      this.setData({
        callInfoList: data.curriculumBigTeacherCallRollMap
      })
    }
  },
  changeCallInfo(data) {
    // 切换大课类型
    let type = data.currentTarget.dataset.index
    this.setData({
      callCurrentType: type
    })
  },
  changeAttendanceStatus(info) {
    // 切换出勤状态
    // if (this.data.courseDetail.curriculumStup != 2) return
    let itemData = info.currentTarget.dataset
    let item = 'callInfoList[' + this.data.callCurrentType + '].value' + '[' + itemData.index + ']' + 'callRollStatus'
    let callRollStatus = itemData.item.callRollStatus
    // if (callRollStatus == 2) return
    let status
    if (itemData.item && parseInt(callRollStatus) < 2) {
      status = parseInt(callRollStatus) + 1
    } else {
      status = 0
    }
    this.setData({
      [item]: status
    })
  },
  async submitAttendance() {
    // 保存考情信息
    let that = this
    try {
      let modal = await wx.showModal({
        title: '提示', // 确认框的标题
        content: '将提交考勤信息，请确认无误！', // 提示信息的内容
      });
      if (modal.confirm) {
        let data = await App.$axios.request({
          url: `/teacher/big/callRoll`,
          method: 'PUT',
          loading: true,
          data: {
            timetableDetailedId: this.data.cid,
            curriculumBigTeacherCallRollMap: this.data.callInfoList
          }
        })
        if (data) {
          that.getDetail(this.data.cid, this.data.courseType)
        }
      } else if (modal.cancel) {
        console.log('用户点击取消');
      }
    } catch (error) {
      console.log('error', error)
    }
  },
  async getHomeWork() {
    // 获取作业详情
    let data = await App.$axios.request({
      url: `/teacher/big/homeWorkInfo/${this.data.cid}`,
      method: 'GET',
      loading: true,
    })
    if (data.id) {
      this.setData({
        homeWorkDetail: data
      })
    }
  },
  homeWorkChange(data) {
    // 作业修改
    let val = data.detail.value
    this.setData({
      'homeWorkDetail.homeWorkContent': val
    })
  },
  async putHomeWork() {
    // 作业提交
    let data = await App.$axios.request({
      url: `/teacher/big/homeWork`,
      method: 'PUT',
      loading: true,
      data: {
        timetableDetailedId: this.data.cid,
        homeWorkContent: this.data.homeWorkDetail.homeWorkContent,
        signCheck: this.data.singStatus
      }
    })
    if (data) {
      this.getDetail(this.data.cid, this.data.courseType)
      wx.showToast({
        title: '操作成功',
      })
    }
  },
  async getFeedbackinfo() {
    //获取-团课-课堂反馈详情
    let data = await App.$axios.request({
      url: `/teacher/big/feedbackInfo/${this.data.cid}`,
      method: 'GET',
      loading: true,
    })
    if (data) {
      this.setData({
        courseFeedback: {
          // feedbackPictureUrl: data.feedbackPictureUrl,
          feedbackVideoUrl: data.feedbackVideoUrl,
          // classSummary: data.classSummary,
          // courseContent: data.courseContent
        },
        'professionalScore.value': data.professionalScore,
        'attitudeScore.value': data.attitudeScore
      })
    }
  },
  changeStar(e) {
    // 修改星星
    let data = e.detail
    let value = [data.type] + '.value'
    this.setData({
      [value]: data.value + 1
    })
  },
  async uploadFile(e) {
    // 上传图片或视频
    let type = e.currentTarget.dataset.filetype
    console.log(type)
    try {
      let files
      // let files = await wx.chooseMedia({
      //   count: 1, // 默认9
      //   sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      //   mediaType: ['mix'], // 文件类型 image  video  mix
      //   sourceType: ['album']
      // });
      if (type == 'image') {
        files = await wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album']
        })
      } else {
        files = await wx.chooseVideo({
          sizeType: ['original', 'compressed'],
          sourceType: ['album'],
          compressed: true
        })
      }
      let file = type == 'image' ? files.tempFilePaths[0] : files.tempFilePath
      let suffix = file.substring(file.indexOf('.'), file.length)
      let url = await App.$axios.request({
        url: `/file/upload`,
        method: 'FILE',
        loading: true,
        filePath: file,
        name: 'file', // 文件字段名，默认为file
        formData: {
          name: `feedbackFile${suffix}`
        }
      })
      console.log(url)
      if (!url) return
      if (type == 'image') {
        this.setData({
          'courseFeedback.feedbackPictureUrl': url
        })
      } else {
        this.setData({
          'courseFeedback.feedbackVideoUrl': url
        })
      }
    } catch (error) {
      console.log(error)
    }
  },
  feedbackChange(data) {
    // 文本域内容修改
    let content = data.currentTarget.dataset.type
    let value = data.detail.value
    let key = 'courseFeedback.' + content
    this.setData({
      [key]: value
    })
  },
  async submitFeedback() {
    // 提交课堂反馈
    let query = {
      ...this.data.courseFeedback,
      professionalScore: this.data.professionalScore.value,
      attitudeScore: this.data.attitudeScore.value
    }
    if (this.testValue(query) === true) {
      let data = await App.$axios.request({
        url: `/teacher/big/feedback`,
        method: 'PUT',
        loading: true,
        data: {
          timetableDetailedId: this.data.cid,
          ...query
        }
      })
      if (data) {
        this.getDetail(this.data.cid, this.data.courseType)
      }
    } else {
      wx.showToast({
        title: this.testValue(query),
        icon: 'none',
        duration: 2000
      })
    }
  },
  testValue(query) {
    // 课堂反馈
    // if (!query.feedbackPictureUrl) {
    //   return '图片未上传'
    // }
    if (!query.feedbackVideoUrl) {
      return '视频未上传'
    }
    if (!query.professionalScore) {
      return '专业未评分'
    }
    if (!query.attitudeScore) {
      return '态度未评分'
    }
    // if (!query.classSummary) {
    //   return '课堂总结不可为空'
    // }
    // if (!query.courseContent) {
    //   return '课程计划不可为空'
    // }
    return true
  },
  async getReviewList() {
    // 团课-作业点评列表
    let data = await App.$axios.request({
      url: `/teacher/big/reviewList/${this.data.cid}`,
      method: 'GET',
      loading: true,
    })
    if (data) {
      this.setData({
        reviewList: data
      })
    }
  },
  jumpReview(item) {
    let itemData = item.currentTarget.dataset.item
    console.log(itemData)
    if (itemData.reviewStatus === 0) return
    wx.navigateTo({
      url: `/pages/homeworkTeacher/homeworkTeacher?id=${itemData.timetableDetailedId}&studentUserId=${itemData.studentUserId}&courseName=${this.data.courseDetail.curriculumName}`,
    })
  }
})
